import threading
from tv import TV
from time import sleep
from utils.debug import *

class Scan(TV):

    def __init__(self, channel_window, scanned):
        '''class for tv scanning, inherit from TV class'''
        TV.__init__(self)
        self.main_window = self.__class__.main_window
        self.channel_window = channel_window
        self.wTree = self.main_window.wTree
        self.scanned = scanned
        self.is_scanning = False
        
    def stop(self):
        '''stop tv scanning'''
        self.main_window._status('off')
        self.main_window._resize_screen(0)
        self.off()
        
        if hasattr(self, 'parser') and self.parser.is_running():
            self.parser.stop()
            delattr(self, 'parser')
        self.is_scanning = False

    def start(self):
        '''start tv scanning, stop tv watching if it active'''
        command = 'mplayer tv:// -tvscan autostart -tv device=%s:outfmt=yuy2' % self.conf.get_conf('tv_card')
        if self.wTree.get_widget('watch_button').get_active():
           self.wTree.get_widget('watch_button').set_active(False)
        sleep(1)
        
        self.main_window._status('scan-start')
        self.on(self.wTree.get_widget('video_area'), command, True)
        self.is_scanning = True
        self.parser = ScanParser(self._scanner, self.main_window, self.channel_window, self.scanned['store'])
        self.parser.start()

class ScanParser(threading.Thread):
    '''
    a thread that read /tmp/scan* file every second the scanning process going on.
    '''
    
    def __init__(self, scanfile, main_window, channel_window, store):
        '''clear the scanned channel list before beginning a new scan'''
        threading.Thread.__init__(self)
        self.thread = threading.Event()
        self.scanfile = scanfile
        self.main_window = main_window
        self.channel_window = channel_window
        self.store = store
        self.store.clear()
    
    def run(self):
        '''
        a loop that read scanning temporary file every one second,
        auto cancel this thread when found 'scan end' line in the temp file
        '''
        import re
        import gtk
        n = 1
        while self.is_running():
            gtk.gdk.threads_enter()
            for line in self.scanfile.readlines():
                if line.startswith('Found new channel:'):
                    channel_freq = re.compile(': \w{2,4}').findall(line, re.IGNORECASE)[0].lstrip(': ')
                    channel_name = '#%s' % n
                    self.store.append([n, channel_name, channel_freq])
                    n += 1
                elif line.startswith('TV scan end'):
                    self.stop()
            gtk.gdk.threads_leave()
            sleep(1)
    
    def stop(self):
        '''enable save button and stop the thread'''
        self.channel_window.widget('savetv_button').set_sensitive(True)
        self.main_window._status('scan-stop')
        self.thread.set()
    
    def is_running(self):
        '''check if the thread is running or not'''
        return not self.thread.isSet()
